"""Determine the correct kpet tree for an NVR."""
import argparse
import re

from cki_lib import misc
from cki_lib import yaml
import sentry_sdk


def map_nvr(kernel_version, nvr_tree_mapping):
    """Return the kpet tree name for an NVR."""
    for tree_name, nvr_regexes in nvr_tree_mapping.items():
        for nvr_regex in misc.flattened(nvr_regexes):
            # any dots not followed by * are literal
            if (nvr_match := re.search(re.sub(r'\.(?!\*)', r'\.', nvr_regex), kernel_version)):
                return tree_name.format_map(nvr_match.groupdict())

    # Raise exception here, so we can fixup tree mapping and restart the pipeline.
    raise RuntimeError('kpet tree name for this NVR could not be matched')


def main(args=None):
    """Run the main command line interface."""
    parser = argparse.ArgumentParser()
    # We want to fix it later, pylint: disable=fixme
    # TODO: Remove once the pipeline stops supplying the option
    parser.add_argument('--package-name',
                        help='kernel binary RPM base name (ignored)')
    parser.add_argument('--kernel-version', help='kernel Version-Release information')
    parser.add_argument('--nvr-tree-mapping', help='nvr-tree mapping data as YAML')
    parser.add_argument('--nvr-tree-mapping-file', help='File with nvr-tree mapping data')
    parsed_args = parser.parse_args(args)

    return map_nvr(parsed_args.kernel_version,
                   yaml.load(file_path=parsed_args.nvr_tree_mapping_file,
                             contents=parsed_args.nvr_tree_mapping))


if __name__ == '__main__':
    misc.sentry_init(sentry_sdk)
    print(main())
